//
//  ListenerList.swift
//  VPai
//
//  Created by devel on 16/9/13.
//  Copyright © 2016年 viatech. All rights reserved.
//

import Foundation

/**
 * A class used to maintain a Listener Object list
 */
class ListenerList {
    private var listeners : [Weak] = []
    
    func registerListener(listener : NSObjectProtocol){
        let w = Weak(value: listener)
        listeners.append(w)
        
        //call foreach just remove wake object
        foreach{ (l : NSObjectProtocol, index) -> Void in
        }
    }
    
    func foreach<T>( iter: (l : T, index : Int)->Void){
        for i in (0 ..< listeners.count).reverse() {
            let weakObj = listeners[i]
            if weakObj.value == nil {
                listeners.removeAtIndex(i)
            }
            else {
                iter(l: weakObj.value! as! T, index: i)
            }
        }
    }
    
    func unregisterListener(listener : NSObjectProtocol){
        foreach{ (l : NSObjectProtocol, index) -> Void in
            if l === listener {
                self.listeners.removeAtIndex(index)
            }
        }
    }
}

private class Weak {
    weak var value : NSObjectProtocol?
    init(value : NSObjectProtocol) {
        self.value = value
    }
}